var uuid = require('node-uuid');
var dateHelper = require('./helper/dateHelper.js');


//######## commonjs interface #################
module.exports = function authContructor(app, redisHelper, config) {

	/** 三种用例：
	 *   1. 只验证应用：appId, secret, username, deviceId
	 *   2. 验证用户身份：appId, secret, deviceId, username, password
	 *   3. 通过token验证用户身份：appId, secret, deviceId, username, accessToken（过滤了一遍请求权限）
	 */
	app.post('/instant/authenticate', function(req, res, next) {
		console.log('\nAuth.----------------------------------------------> ' + dateHelper.getNowFormatTime());
		console.log('Request：request coming：' + req.ip);
		console.log('Request body:');
		console.log(req.body);

		// 验证设备，唯一标识 Hash(deviceId_pushToken, push_Token)
		var deviceId = req.body.deviceId;
		var username = req.body.username;

		if ( /*config.APP_ID !== req.body.appId || config.APP_SECRET !== req.body.secret ||*/ deviceId === undefined || deviceId === '' || username === undefined || username === '') {
			res.status(401).json({
				code: 401,
				status: 'Unauthorized',
				message: 'app validation fail. please check query params'
			});
			return;
		};
		// 生成token令牌
		var push_Token = uuid.v4();

		//################## 缓存token鉴权令牌 ##################
		redisHelper.set(username + deviceId + '_pushToken', push_Token + '@' + Date.now(), '', function(error, reply) {
			if (!error) {
				console.log('resdis save [token]...' + push_Token);
				res.status(200).json({
					"result": true,
					"host": '121.199.39.92',
					"port": 8868,
					"push_Token": push_Token,
					'expired': dateHelper.getNowFormatTime(),
					'expired_day': 1
				}); // 缓存一天
			} else {
				console.log('resdis set error [token]...' + reply);
				next(new Error(JSON.stringify({
					code: 500,
					result: false,
					status: 'server exception',
					message: 'server exception. redis net exc that maybe connection disable.'
				})));
			}
		});
	});
}